import { ref, computed, watch } from 'vue'
import { useFreightForwarderStore } from './sharedFreightData'
import { storeToRefs } from 'pinia'
import AirFreightContent from './AirFreightContent.vue'
import FCLFreightContent from './FCLFreightContent.vue'
import LCLFreightContent from './LCLFreightContent.vue'
import OrgPortChargesContent from './OrgPortChargesContent.vue'
import DstPortChargesContent from './DstPortChargesContent.vue'
import { getCalculatorData } from './sharedFreightData'



export function useFreightForwarder(props, emit) {
    const store = useFreightForwarderStore()
    const { freightForwarderData } = storeToRefs(store)

    const activeSubTab = ref('air')
    const subTabs = ['air', 'fcl', 'lcl', 'originPortCharges', 'destinationPortCharges']
    const subTabsDisplay = ['空运', 'FCL运费', 'LCL/FTL/TL/COU Freight', '起运港费用', '目的港费用']

    const selectedCalculator = ref(null)
    const calculators = getCalculatorData()

    const currentSubComponent = computed(() => {
        const componentMap = {
            air: AirFreightContent,
            fcl: FCLFreightContent,
            lcl: LCLFreightContent,
            originPortCharges: OrgPortChargesContent,
            destinationPortCharges: DstPortChargesContent
        }
        return componentMap[activeSubTab.value]
    })

    const setActiveSubTab = (tab) => {
        activeSubTab.value = tab
    }

    const updateFreightForwarderData = (newData) => {
        store.setFreightForwarderData(newData);
        emit('update:freightForwarderData', store.freightForwarderData);
    }

    const getCurrentBusinessId = computed(() => {
        const currentBusiness = store.getBusinessByType(activeSubTab.value)
        return currentBusiness?.id || `new-${activeSubTab.value}-${Date.now()}`
    })

    watch(() => props.freightForwarderData, (newValue) => {
        console.log('Received new freightForwarderData:', newValue);
        if (newValue) {
            store.setFreightForwarderData(newValue);
        }
    }, { deep: true });

    return {
        activeSubTab,
        subTabs,
        subTabsDisplay,
        currentSubComponent,
        setActiveSubTab,
        updateFreightForwarderData,
        getCurrentBusinessId,
        selectedCalculator,
        calculators,
        freightForwarderData  // 添加这行，确保 freightForwarderData 可以在组件中使用
    }
}
